<?php

// +----------------------------------------------------------------------
// | 分销管家
// +----------------------------------------------------------------------
// | Copyright (c) 2015 http://www.kmeen.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzake <http://www.kmeen.com>
// +----------------------------------------------------------------------

namespace Common\Model;

use Think\Model;
use Think\Log;

/**
 * 分类模型
 * @author xzake
 */
class MemberModel extends Model {

    /**
     * 自动验证规则
     * @author xzake
     */
    protected $_validate = array(
        array('name', 'require', '真实姓名不能为空', self::MUST_VALIDATE, 'regex', self::MODEL_UPDATE),
        array('nickname', '1,30', '真实姓名长度为1-30个字符', self::EXISTS_VALIDATE, 'length', self::MODEL_UPDATE),
        //验证邮箱
//        array('email', 'email', '邮箱格式不正确', self::EXISTS_VALIDATE, 'regex', self::MODEL_UPDATE),
//        array('email', '1,32', '邮箱长度为1-32个字符', self::EXISTS_VALIDATE, 'length', self::MODEL_UPDATE),
//        array('email', '', '邮箱被占用', self::EXISTS_VALIDATE, 'unique', self::MODEL_UPDATE),
        //验证手机号码
        array('phone', '/^1\d{10}$/', '手机号码格式不正确', self::EXISTS_VALIDATE, 'regex', self::MODEL_UPDATE),
        array('phone', '', '手机号被占用', self::EXISTS_VALIDATE, 'unique', self::MODEL_UPDATE),
    );

    /**
     * 自动完成规则
     * @author xzake
     */
    protected $_auto = array(
        array('create_time', NOW_TIME, self::MODEL_INSERT),
        array('update_time', NOW_TIME, self::MODEL_BOTH),
        array('status', '1', self::MODEL_INSERT),
    );

    public function saveUsers($fromusername, $ticket = FALSE, $idenify = "ticket") {

        $data = array();

        $map = array();

        if (is_array($fromusername)) {

            $data = $fromusername;

            #不存在openid,参数有误
            if (!isset($data["openid"])) {

                return false;
            }

            $map["openid"] = array("eq", $data["openid"]);
        } else {

            $idenify = "ticket";

            $map["openid"] = array("eq", $fromusername);

            $data['openid'] = $fromusername;
        }

        $temp = $this->where($map)->find();

        if (empty($temp)) {

            if ($ticket) {
                #这里ticket表示传进来的会员id
                #$idenity = 'id'
                $map = array();  //清空$map

                $map[$idenify] = array("eq", $ticket);

                $parent = $this->where($map)->find();

                if (empty($parent)) {

                    #没有找到传递id值得会员信息(>﹏<。)～呜呜呜……
                    #这里按添加 普通用户处理 o((≧▽≦o)太好笑了！！
                    return false;
//                    return $this->saveNormalUser($data);
                } else {

                    return $this->saveTicketUser($data, $parent);
                }
            } else {

                return $this->saveNormalUser($data);
            }
        }
    }

    /*
     * 普通用户关注（没有推荐信息）
     */

    private function saveNormalUser($data) {

        $data['pid'] = 0;
        $data['lft'] = 1;
        $data['rgt'] = 2;
        $data['lvl'] = 0;
        $data['flag'] = 0;
        $data['create_time'] = $data['update_time'] = NOW_TIME;
        $data['status'] = 1;

        Log::write("准备写入用户信息:" . json_encode($data));

        $id = $this->add($data);

        if (id) {
            Log::write("写入用户信息成功:$id");
            $td["id"] = $id;
            $td["flag"] = $id;
            $this->save($td);
            return $id;
        }

        Log::write("普通用户注册失败" . time() . '-' . json_encode($data));
        return false;
    }

    /*
     * 推荐用户注册
     * 
     * &data 微信网页授权获取的用户信息
     * &parent 父级的个人信息
     */

    private function saveTicketUser($data, $parent) {

        $pkey = $parent['rgt'];
        //下级把父右值作为自己的左值，自己的右值等于左值+1
        $data['pid'] = $parent['id'];
        $data['lft'] = $pkey;
        $data['rgt'] = $pkey + 1;
        $data['lvl'] = $parent['lvl'] + 1;
        $data['flag'] = $parent['flag'];
        $data['create_time'] = $data['update_time'] = NOW_TIME;
        $data['status'] = 1;
        $id = $this->add($data);

        if ($id) {

            $rmap = array();
            $rmap["flag"] = array("eq", $parent['flag']);
            $rmap["rgt"] = array("egt", $pkey); //大于或等于
            $rmap["id"] = array("neq", $id);
            $this->where($rmap)->setInc('rgt', 2);
            $lmap = array();
            $lmap["flag"] = array("eq", $parent['flag']);
            $lmap["lft"] = array("gt", $pkey); //大于
            $lmap["id"] = array("neq", $id);
            $this->where($lmap)->setInc('lft', 2);

            return $id;  //返回注册用户的id
        }

        Log::write("推荐用户注册失败" . time() . '-' . json_encode($data));
        return false;
    }

    /**
     * 用户登录
     * @author xzake
     */
    public function login($data) {

        $map['openid'] = array('eq', $data['openid']);

        $user = $this->where($map)->find(); //根据微信网页授权获取到的用户openid,查找会员数据

        $id = 0;

        #查找无此用户
        if (!$user) {

            if (isset($data["id"])) {
                #存在$id(链接邀请)
                $id = $data["id"];

                unset($data["id"]);

                #data微信网页获取的用户信息，$id传值近来的会员id
                $id = $this->saveUsers($data, $id, "id");
            } elseif (isset($data["ticket"])) {
                #二维码推荐会员
                $ticket = $data["ticket"];

                unset($data["ticket"]);

                $id = $this->saveUsers($data, $ticket, "ticket");
            } else {

                $id = $this->saveUsers($data);
            }

            #新增内容，防止下面autoLogin登录$user信息为空
            $user = $this->where('id =' . $id)->find(); //根据返回的新注册用户id,查找出数据
        }
      
        //更新登录信息
        $sdata = array(
            'id' => empty($user) ? $id : $user['id'],
            'nickname' => $data['nickname'],
            'info' => $data['info'],
            'login_count' => array('exp', '`login_count`+1'),
            'login_time' => NOW_TIME,
            'login_ip' => get_client_ip(1),
        );

        $this->save($sdata);

        $this->autoLogin($user);

        #user为空返回的是新注册用户的信息；反之返回的是已经注册的用户id
        return $user['id'];
//        return empty($user) ? $id : $user['id'];
    }

    /**
     * 设置登录状态
     * @author xzake
     */
    public function autoLogin($user) {

        //记录登录SESSION和COOKIES
        $auth = array(
            'uid' => $user['id'],
            'login_time' => $user['login_time'],
            'login_ip' => get_client_ip(1),
        );

        session('member_auth', $auth);

        session('member_auth_sign', $this->dataAuthSign($auth));
    }

    /**
     * 数据签名认证
     * @param  array  $data 被认证的数据
     * @return string       签名
     * @author xzake
     */
    public function dataAuthSign($data) {
        //数据类型检测
        if (!is_array($data)) {

            $data = (array) $data;
        }

        ksort($data); //排序

        $code = http_build_query($data); //url编码并生成query字符串

        $sign = sha1($code); //生成签名

        return $sign;
    }

    /**
     * 检测用户是否登录
     * @return integer 0-未登录，大于0-当前登录用户ID
     * @author xzake
     */
    public function isLogin() {

        $user = session('member_auth');

        if (empty($user)) {

            return 0;
        } else {

            return session('member_auth_sign') == $this->dataAuthSign($user) ? $user['uid'] : 0;
        }
    }

    /*
     * 统计会员的余额
     * 
     * @return array status 处理状态  msg 相关信息
     */

    public function member_balance($user_id) {

        //会员收入
        $array_member_income = $this->member_income($user_id);

        if (!$array_member_income['status']) {

            return $array_member_income;
        }

        $member_income = $array_member_income['msg'];


        //会员支出
        $array_member_expense = $this->member_expense($user_id);

        if (!$array_member_expense['status']) {

            return $array_member_expense;
        }

        $member_expense = $array_member_expense['msg'];

        $member_balance = sprintf('%.2f', ($member_income - $member_expense)); //会员余额

        return array('status' => 1, 'msg' => $member_balance);
    }

    /*
     * 统计会员的(积分)金额消耗
     * 
     * @内容：提现(kmeen_member_cash) 和 转赠(kmeen_member_sendscore)
     * @return 
     */

    public function member_expense($user_id) {

        if (empty($user_id)) {

            return array('status' => FALSE, 'msg' => '参数丢失，请重试！');
        }

        $cash_model = D('MemberCash');

        $sendscore_model = D('MemberSendscore');

        $order_model = D('Order');

        #提现(积分)金额
        //cash['list'] 提现列表、cash['num] 提现金额
        $cash = $cash_model->member_cash($user_id);

        #（积分）金额转出
        $sendscore = $sendscore_model->member_sendscore($user_id, 1);

        #积分消费
        $pay_points = $order_model->get_member_order_amount($user_id, 2, 0);

        $total = sprintf('%2f', $cash['msg']['num'] + $sendscore['msg']['num'] + $pay_points['msg']['num']);

        return array('status' => 1, 'msg' => $total);
    }

    /*
     * 统计会员的所有收入
     * 
     * @内容：三级分佣 、 全返金额 、 团队提成 和 公排奖励
     */

    public function member_income($user_id) {

        if (empty($user_id)) {

            return array('status' => FALSE, 'msg' => '参数丢失，请重试！');
        }

        #会员的公排奖励
        $publicrow = D('Gongpai')->gp_reward($user_id);

        $publicrow_reward = $publicrow['msg']['num'];

        #全返金额
        $fullback = D('MemberFullback')->member_fullback($user_id);

        $fullback_money = $fullback['msg']['num'];

        #团队分红
        $team = D('MemberTeamdividend')->member_teamdividend($user_id);

        $team_dividend = $team['msg']['num'];

        $manage = D('MemberManagerewards')->manage_teamdividend($user_id);

        $manage_dividend = $manage['msg']['num'];

        #三级分佣
        $commission = D('MemberCommission')->member_commission($user_id);

        $member_commission = $commission['msg']['num'];

        #获得的赠送积分
        $getscore = D('MemberSendscore')->member_sendscore($user_id, 2);

        $member_get_score = $getscore['msg']['num'];

        $total = sprintf('%.2f', ($publicrow_reward + $fullback_money + $team_dividend + $manage_dividend + $member_commission + $member_get_score));

        return array('status' => 1, 'msg' => $total);
    }

    /*
     * 会员的下级会员信息
     * 
     * @user_id 会员id  floor 获取会员的多少层会员
     * 
     * @range TRUE 表示计算会员floor级內的会员数  FALSE 表示计算会员floor级的会员数
     * 
     * @spend TRUE 表示消费会员 FALSE所有会员
     * 
     * @return status 执行状态  msg 团队会员列表
     */

    public function members_team($user_id, $floor = 1, $range = FALSE, $spend = FALSE) {

        $info = $this->find($user_id);

        if (empty($info)) {

            return array('status' => FALSE, 'msg' => '会员不存在！');
        }

        #是否消费
        if ($spend) {

            $map['total_spend'] = array('gt', 0); //表示消费用户
        }
        $map['flag'] = $info['flag']; //锁定在同一个团队
        $map['lft'] = array('gt', $info['lft']);
        $map['rgt'] = array('lt', $info['rgt']);

        #多级及单级判段
        if ($range) {

            $map['lvl'] = array('between', array($info['lvl'], $info['lvl'] + $floor));
        } else {

            $map['lvl'] = array('eq', $info['lvl'] + $floor);
        }

        $team_list = $this->where($map)->order('id')->select();

        return array('status' => 1, 'msg' => $team_list);
    }

    /*
     * 全返会员信息
     * 
     * @param $level 推荐会员等级数 
     * @param $members_num 推荐（消费）人数 
     * @param $members_income  收入金额上线条件
     */

    public function get_members_fullback($level = 1, $members_num = 1, $members_income = 0.00) {

        $fullback_members = $this->where('total_spend > 0 and (rgt - lft - 1)/2 > 0 ')->select(); //检索出消费会员 和 初步检索出有推荐下级的会员

        if ($members_num > 1) {

            foreach ($fullback_members as $k => $v) {

                //判段会员在推荐等级内的消费会员数
                $array_recommended_members = $this->members_team($v['id'], $level, TRUE);

                if (!$array_recommended_members['status']) {

                    return $array_recommended_members;
                }

                $recommended_members_number = count($array_recommended_members['msg']);

                if ($recommended_members_number < $members_num) {

                    unset($fullback_members[$k]);
                }

                //判段会员的总收入金额

                if ($members_income > 0) {

                    $array_members_income = $this->member_income($v['id']);

                    if (!$array_members_income['status']) {

                        return $array_members_income;
                    }

                    $income = $array_members_income['msg'];

                    if ($members_income <= $income) {

                        unset($fullback_members[$k]);
                    }
                }
            }
        }

        return array('status' => 1, 'msg' => $fullback_members);
    }

    /*
     *  是否是799代理
     *  Author: cys 
     */

    public function checkMaxLvl($memberId) {


        $curr_user = $this->where("id=" . $memberId)->find();

        $curr_user['max_lvl'] == 0 ? $result = 0 : $result = 1;

        return $result;
    }

    
    
    /*
     *  判断上级会员是否被允许接受返利
     *  @param $user_total_spend 上级会员累计消费金额
     *  @param $current_member_spend 支付会员的消费金额
     *  @param $up_user_id 上级会员ID
     * 499会员吸取两级，799会员吸取三级，执行董事不管累计消费多少都吸取三级,同时只返直推1级
     *  Author: cys 
     */

    public function checkIdentity($user_total_spend, $user_level, $current_member_spend, $memberId,$up_user_id) {

        $max_level = $this->checkMaxLvl($memberId);
        $up_manage = $this->checkManage($up_user_id);
       $self_manage = $this->checkManage($memberId);

        if ((($current_member_spend >= 799) && $max_level == 1) || $self_manage==1) {
            $result = 2;
            return $result;
        }

        switch ($user_level) {
            case 0:
                $result = 1;
                break;
            case 1:
                ((($user_total_spend >= 399) && $user_level == 1) || $up_manage==1 )== true ? $result = 1 : $result = 0;
                break;
            case 2:
                ((($user_total_spend >= 799) && $user_level == 2) || $up_manage==1 )== true ? $result = 1 : $result = 0;
                break;
        }

        return $result;
    }

    /*
     *  获取会员的真实商品价格
     */

    public function getPrice($price, $user_id) {

        $user = M('Member')->where("id=" . $user_id)->field('total_spend, manage')->find();
        
        if ( $user['manage']==1) {
               $price *= C('FX_MANAGE_SCARE') / 10 ;
        }else if( $user['total_spend'] >= 799) {
               $price *=  C('FX_USER_DISCOUNT')/ 10 ;
        }

        $price = sprintf('%.2f', $price);

        return $price;
    }

    public function returnMaxLvlMoney($commission_total_fact) {
        return $commission_total_fact *= C('FX_USER_SCARE') / 100;
    }

    /*
     *  查询执行董事
     *  @param $count 直推799会员人数到$count则为执行董事
     */
    public function getManagers($count) {
        $pid_arry = M()->query("SELECT `pid` FROM `kmeen_member` GROUP BY pid ,max_lvl  
                                                      HAVING count(pid)>={$count} and COUNT(max_lvl=1)>={$count}");
           if (!empty($pid_arry)) {
                 foreach ($pid_arry as $value) {
              $pid_list[] = $value['pid'];
          }

          $pid_str = implode(",", $pid_list);
          $manager_list = $this->where(array("id" => array("in", $pid_str)))->select();
           }
     
        return $manager_list;
    }

    /*
     *  判断执行董事
     *  Author: cys 2016-11-21
     */

    public function checkManage($user_id) {
        $members = M("Member")->where("id={$user_id}")->field("manage")->find();

        $members['manage']==1 ? $result = 1 : $result = 0;

        return $result;
    }

}
